const BASE_URL = 'http://localhost:8080/api';

class Request {
	constructor() {
		this.baseURL = BASE_URL;
		this.interceptors = {
			request: [],
			response: []
		};
		this.isRefreshing = false;
		this.requests = [];
		
		// 初始化拦截器
		this._setupInterceptors();
	}

	// 初始化拦截器
	_setupInterceptors() {
		// 请求拦截器 - 自动添加token（优先级最高）
		this.useRequestInterceptor(async (config) => {
			console.log('🚀 请求拦截器开始:', config.url);
			
			// 确保header存在
			config.header = config.header || {};
			
			// 设置默认Content-Type
			if (!config.header['Content-Type']) {
				config.header['Content-Type'] = 'application/json';
			}
			
			// 跳过认证的请求列表
			const skipAuthUrls = [
				'/auth/login',
				'/auth/register',
				'/auth/refresh',
				'/auth/captcha',
				'/public/'
			];
			
			// 判断是否需要跳过认证
			const shouldSkipAuth = config.skipAuth || skipAuthUrls.some(url => 
				config.url.includes(url)
			);
			
			console.log(`🔐 认证检查: ${config.url}, 跳过认证: ${shouldSkipAuth}`);
			
			// 如果不是跳过认证的请求，添加token
			if (!shouldSkipAuth) {
				const token = this.getAccessToken();
				console.log('🔑 获取到的token:', token ? '存在' : '不存在');
				
				if (token) {
					config.header['Authorization'] = `Bearer ${token}`;
					console.log('✅ Token已添加到请求头');
				} else {
					console.warn('⚠️ 需要认证的请求但没有token');
					// 立即跳转到登录页，而不是继续请求
					this._redirectToLogin();
					throw new Error('未登录，无法访问需要认证的接口');
				}
			}
			
			return config;
		});
		
		// 响应拦截器 - 统一错误处理
		this.useResponseInterceptor(async (response) => {
			console.log('📨 响应拦截器:', response);
			
			// 处理HTTP错误
			if (response.statusCode && response.statusCode !== 200) {
				if (response.statusCode === 401) {
					this.handleUnauthorized();
					throw new Error('登录已过期，请重新登录');
				}
				
				const errorMsg = response.data?.message || `请求失败 (${response.statusCode})`;
				uni.showToast({
					title: errorMsg,
					icon: 'none',
					duration: 2000
				});
				throw new Error(errorMsg);
			}
			
			// 处理业务逻辑错误
			if (response.code !== undefined && response.code !== 200) {
				const errorMsg = response.message || '请求失败';
				uni.showToast({
					title: errorMsg,
					icon: 'none',
					duration: 2000
				});
				throw new Error(errorMsg);
			}
			
			return response;
		});
	}
	
	// 跳转到登录页
	_redirectToLogin() {
		uni.showModal({
			title: '登录提示',
			content: '请先登录',
			showCancel: false,
			success: () => {
				uni.reLaunch({
					url: '/pages/login/login'
				});
			}
		});
	}

	// 添加请求拦截器
	useRequestInterceptor(interceptor) {
		this.interceptors.request.push(interceptor);
	}

	// 添加响应拦截器
	useResponseInterceptor(interceptor) {
		this.interceptors.response.push(interceptor);
	}

	// 执行请求拦截器
	async runRequestInterceptors(config) {
		let currentConfig = { ...config };
		for (const interceptor of this.interceptors.request) {
			currentConfig = await interceptor(currentConfig);
		}
		return currentConfig;
	}

	// 执行响应拦截器
	async runResponseInterceptors(response) {
		let currentResponse = { ...response };
		for (const interceptor of this.interceptors.response) {
			currentResponse = await interceptor(currentResponse);
		}
		return currentResponse;
	}

	// 获取访问令牌
	getAccessToken() {
		// 尝试多种可能的token存储键名
		return uni.getStorageSync('accessToken') || 
			   uni.getStorageSync('token') || 
			   uni.getStorageSync('userToken');
	}

	// 获取刷新令牌
	getRefreshToken() {
		return uni.getStorageSync('refreshToken');
	}

	// 设置令牌
	setToken(tokenData) {
		if (tokenData.accessToken || tokenData.token) {
			const token = tokenData.accessToken || tokenData.token;
			uni.setStorageSync('accessToken', token);
			uni.setStorageSync('token', token); // 兼容性存储
		}
		if (tokenData.refreshToken) {
			uni.setStorageSync('refreshToken', tokenData.refreshToken);
		}
		if (tokenData.expiresIn) {
			const expireTime = Date.now() + tokenData.expiresIn;
			uni.setStorageSync('tokenExpireTime', expireTime);
		}
	}

	// 清除令牌
	clearToken() {
		['accessToken', 'token', 'userToken', 'refreshToken', 'tokenExpireTime', 'userInfo'].forEach(key => {
			uni.removeStorageSync(key);
		});
	}

	// 检查令牌是否即将过期
	isTokenExpiringSoon(threshold = 300000) {
		const expireTime = uni.getStorageSync('tokenExpireTime');
		if (!expireTime) return true;
		return expireTime - Date.now() < threshold;
	}

	// 刷新令牌
	async refreshToken() {
		if (this.isRefreshing) {
			return new Promise((resolve, reject) => {
				this.requests.push({ resolve, reject });
			});
		}

		this.isRefreshing = true;
		const refreshToken = this.getRefreshToken();

		if (!refreshToken) {
			this.clearToken();
			throw new Error('没有可用的刷新令牌');
		}

		try {
			const response = await this._request({
				url: '/auth/refresh',
				method: 'POST',
				data: { refreshToken },
				skipAuth: true
			});

			if (response.code === 200 && response.data) {
				this.setToken(response.data);
				this.requests.forEach(({ resolve }) => resolve());
				this.requests = [];
				return response.data;
			} else {
				throw new Error(response.message || '刷新令牌失败');
			}
		} catch (error) {
			this.requests.forEach(({ reject }) => reject(error));
			this.requests = [];
			this.clearToken();
			throw error;
		} finally {
			this.isRefreshing = false;
		}
	}

	// 内部请求方法
	_request(options) {
		return new Promise((resolve, reject) => {
			uni.request({
				url: this.baseURL + options.url,
				method: options.method || 'GET',
				data: options.data || {},
				header: options.header || {},
				success: (res) => {
					resolve(res);
				},
				fail: (err) => {
					reject(err);
				}
			});
		});
	}

	// 主请求方法
	async request(options) {
		try {
			// 执行请求拦截器
			const finalConfig = await this.runRequestInterceptors(options);

			let response;

			// 检查token是否即将过期
			if (!finalConfig.skipAuth && this.isTokenExpiringSoon()) {
				try {
					await this.refreshToken();
				} catch (refreshError) {
					console.warn('Token刷新失败:', refreshError);
				}
			}

			// 发送请求
			response = await this._request(finalConfig);

			// 执行响应拦截器
			response = await this.runResponseInterceptors(response);

			return response;

		} catch (error) {
			console.error('请求失败:', error);
			throw error;
		}
	}

	// 处理未授权错误
	handleUnauthorized() {
		this.clearToken();
		uni.showToast({
			title: '登录已过期，请重新登录',
			icon: 'none',
			duration: 2000
		});

		setTimeout(() => {
			uni.reLaunch({
				url: '/pages/login/login'
			});
		}, 1500);
	}

	// 快捷方法
	get(url, data = {}, config = {}) {
		return this.request({ ...config, url, method: 'GET', data });
	}

	post(url, data = {}, config = {}) {
		return this.request({ ...config, url, method: 'POST', data });
	}

	put(url, data = {}, config = {}) {
		return this.request({ ...config, url, method: 'PUT', data });
	}

	delete(url, data = {}, config = {}) {
		return this.request({ ...config, url, method: 'DELETE', data });
	}
}

// 创建请求实例（不需要重复添加拦截器）
const request = new Request();

export default request;